use std::io::Cursor;
use std::io::Read;

use aesstream::AesReader;
use m3u8_rs::Key as m3u8Key;
use m3u8_rs::KeyMethod;
use serde::Deserialize;
use serde::Serialize;

use crate::utils::parse_m3u8_url_get_host_and_baseurl;

#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
pub enum KeyType {
    None,
    Aes128,
    SampleAes,
}

#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
pub struct Key {
    pub ty: KeyType,
    pub iv: Option<String>,
    pub content: Vec<u8>,
}

impl Default for Key {
    fn default() -> Self {
        Key {
            ty: KeyType::None,
            iv: None,
            content: vec![],
        }
    }
}

impl Key {
    pub fn from_key(k: &m3u8Key) -> Result<Self, String> {
        match k.method {
            KeyMethod::None => Ok(Key {
                ty: KeyType::None,
                iv: k.iv.clone(),
                content: vec![],
            }),
            KeyMethod::AES128 => {
                Ok(Key {
                    ty: KeyType::Aes128,
                    iv: k.iv.clone(),
                    // content: download(&Url::parse(k.uri.as_ref().unwrap())?).await?
                    content: vec![],
                })
            }
            _ => Err(format!("Unsupported key method: {}", &k.method)),
        }
    }

    pub fn decode(&self, data: &[u8]) -> Vec<u8> {
        let decryptor = crypto::aessafe::AesSafe128Decryptor::new(&self.content);
        let mut reader = AesReader::new(Cursor::new(data), decryptor).unwrap();
        let mut v = Vec::new();
        match reader.read_to_end(&mut v) {
            Ok(_) => v,
            Err(_) => data.clone().to_vec(),
        }
    }
}

// 下载Key
pub async fn download_key(k: &m3u8Key, base_url: &str) -> Key {
    let k_url = k.uri.clone().unwrap();

    let k_url = if k_url.starts_with("http") {
        k_url
    } else if k_url.starts_with("/") {
        let (host, _) = parse_m3u8_url_get_host_and_baseurl(base_url).unwrap();
        format!("{host}{k_url}")
    } else {
        format!("{base_url}{k_url}")
    };

    let mut _key = Key::from_key(k).unwrap();

    let Ok(k_resp) = reqwest::get(&k_url).await else { panic!( "Key[{}] 访问失败",&k_url ) } ;

    _key.content = k_resp.bytes().await.unwrap().to_vec();

    let con_str = _key.content.clone();
    let con_str = String::from_utf8(con_str);

    println!("获取Key的URL:{k_url}");
    println!("KEY的值:{con_str:?}");

    _key
}
